import React, {
  Component, PureComponent
} from 'react';
import {
  Text,
  ListView,
  RefreshControl,
  View,
  StyleSheet,
  Image,
  Button,
  Alert,
  FlatList,
  InteractionManager,
  NativeModules,
  Modal,
  TextInput,
  TouchableHighlight
} from 'react-native';
import {connect} from 'react-redux';

import styles from './styles'

import {getOrderList,refreshOrderList,orderCancle,orderToSend}  from './actions'

import {toast} from '../../utils/NativeUtil';
import {naviPush} from '../../navigatorApp/actions'
import CLAlertWithInput from '../../component/CLAlertWithInput'

import OrderItem from './orderItem'

class OrderFragment extends PureComponent {
  constructor(props) {
    super(props);
    this.page = 1;
    this.size = 10;
    this.orderState = props.orderState;
    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    });
    this.orderNo = undefined;
    this.state = {
      dataSource: ds,
      footText: "下拉加载更多",
      expressNo:"",
      visible:false,
    };
  }

  setFootText = (text) => {
        var showText = "";
        showText = text;
        if (showText == "加载完成"){
            if (this.props.hasMore){
                showText = "上拉加载更多";
            }
        }
        this.setState({
            footText: showText
        })
  }

  loadMore = () => {
    this.page = this.page + 1;
    const self = this;
    this.props.getOrderList(this.props.token,this.orderState,this.page,
        function(){
            self.setFootText("正在加载");
        },
        function(){
            self.setFootText("加载完成");
        },
        function(){
             self.setFootText("加载失败，下拉重新加载");
        }
    );
  }

  onRefresh = () => {
    this.page = 1;
    this.refreshOrderList();
  }

  refreshOrderList = () => {
        const self = this;
        this.props.refreshOrderList(this.props.token,this.orderState,this.page,
            function(){
                self.setFootText("加载完成");
            },
            function(){
                self.setFootText("加载失败，下拉重新加载");
            }
        );
  }

  componentDidMount() {
    this.page = 1;
    InteractionManager.runAfterInteractions(() => {
        this.refreshOrderList();
    });
  }

  renderFooter = () => {
    return <View style={{ margin:10,flex: 1,flexDirection: 'row',justifyContent: 'center'}} >
            <Text style={styles.grayFont}>{this.state.footText}</Text>
        </View>
  }

  orderCancleDialog = (id) => {
  var self = this;
  return function(){
    Alert.alert(
      '是否取消订单',
      '取消则按确定,否则点取消',
      [
        {text: '确定', onPress: () => self.orderCancle(id)},
        {text: '取消', onPress: () => console.log('Bar Pressed!')},
      ]
    );
  }
  }

  orderCancle = (id) => {
    var self = this;

      const params = {
        token: this.props.token,
        orderId: id
      };

      this.props.orderCancle(params,
            function(){
                self.onRefresh();
            },
            function(){

            }
      )
  }

  orderToSendDialog = (id) => {
    var self = this;
    
    
    return function(){
        self.orderNo = id;
        self.setState({visible:true});
    }
  }

  cancleSend = () => {
      var self = this;
      return function(){
           self.setState({visible:false});
      }
 
  }

  modalClose = () => {
      var self = this;
      return function(){
           self.setState({visible:false});
      }
  }

  submitSend = () => {
        var self = this;

        return function(){
            if(self.state.expressNo == ""){
                toast("请输入物流单号");
                return;
            }

            self.setState({visible:false});

            const params = {
                token: self.props.token,
                orderId: self.orderNo,
                expressNo:self.state.expressNo,
                expressType:'auto'
            };

            self.props.orderToSend(params,
                    function(){
                        self.onRefresh();
                    },
                    function(){

                    }
            )
        }
        
  }

  showLogistics = (id) => {
      var self = this;
      return function() {
        self.props.naviPush('logistics', {orderid: id});
      }
  }

  _renderItem = ({item}) => {
    return <OrderItem 
    orderType={this.orderState}
    order={item} 
    orderCancleDialog={this.orderCancleDialog} orderToSendDialog={this.orderToSendDialog} showLogistics={this.showLogistics} />
  }

  renderSeparator = () => {
    return (<View style={{ backgroundColor: '#eee',height:10}} />)
  }

  onEndReached = () => {
    if (this.props.hasMore == true) {
        this.loadMore();
    }
  }

  render() {
      var orderList = [];

      if (this.props.orderState == 2){
          orderList = this.props.orderList2
      }else  if (this.props.orderState == 3){
          orderList = this.props.orderList3
      }else  if (this.props.orderState == 6){
          orderList = this.props.orderList6
      }else  if (this.props.orderState == 7){
          orderList = this.props.orderList7
      }else  if (this.props.orderState == 10){
          orderList = this.props.orderList10
      }
      
    return ( 
        <View style={{flex: 1, width: null, height: null}}>
        <FlatList
                style={{flex: 1}}
                ItemSeparatorComponent={this.renderSeparator}
                data={orderList}
                renderItem={this._renderItem}
                ListFooterComponent={this.renderFooter}
                onEndReached={this.onEndReached}
                onEndReachedThreshold={0}
                onRefresh={this.onRefresh}
                refreshing={this.props.loading}
            />
      <CLAlertWithInput 
        onChangeText = {(text) => {this.setState({ expressNo: text })}}
        visible = {this.state.visible}
        submit={this.submitSend()}
        cancle={this.cancleSend()}
        modalClose = {this.modalClose()}
      />
      </View>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    token: state.mainmodel.token, 
    orderList2: state.order.orderList2,
    orderList3: state.order.orderList3,
    orderList6: state.order.orderList6,
    orderList7: state.order.orderList7,
    orderList10: state.order.orderList10,
    hasMore:state.order.hasMore,
    loading:state.request.loading,
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    naviPush:(routerName, params) => {
        dispatch(naviPush(routerName, params))
    },
    getOrderList: (token, orderState, page,start,success,error) => {
        dispatch(getOrderList(token, orderState, page,start,success,error))
    },
    refreshOrderList: (token, orderState, page,success,error) => {
        dispatch(refreshOrderList(token, orderState, page,success,error))
    },
    orderCancle:(params,success,error) => {
        dispatch(orderCancle(params,success,error));
    },
    orderToSend:(params,success,error) => {
        dispatch(orderToSend(params,success,error));
    },
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(OrderFragment);

